package com.fjh.springboot_01.controller;

import com.fjh.springboot_01.pojo.Result;

import com.fjh.springboot_01.pojo.tutor.TutoringSchedule;
import com.fjh.springboot_01.service.TutoringScheduleService;
import com.fjh.springboot_01.mapper.TutoringMapper;
import com.fjh.springboot_01.mapper.TutoringBookingMapper;
import com.fjh.springboot_01.mapper.TutoringScheduleMapper;
import com.fjh.springboot_01.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import com.fjh.springboot_01.mapper.PaymentOrderMapper;
import com.fjh.springboot_01.pojo.payment.PaymentOrder;
import java.util.HashMap;
import java.time.LocalDateTime;
import com.fjh.springboot_01.utils.PaymentHelper;


@RestController
@RequestMapping("/tutoring/schedule")
public class TutoringScheduleController {
    @Autowired
    private TutoringScheduleService scheduleService;
    
    @Autowired
    private TutoringMapper tutoringMapper;
    
    @Autowired
    private TutoringBookingMapper bookingMapper;
    
    @Autowired
    private TutoringScheduleMapper tutoringScheduleMapper;
    
    @Autowired
    private PaymentOrderMapper paymentOrderMapper;

    // 创建时间安排
    @PostMapping("/create")
    public Result<String> createSchedule(@RequestBody TutoringSchedule schedule) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 0) {
            return Result.error("只有学生可以创建时间安排");
        }
        
        schedule.setStudentId(userId);
        schedule.setStatus(0); // 设置为待确认状态
        schedule.setCreatedBy("STUDENT"); // 设置创建者为学生
        
        // 使用前端传递的teacherId，如果没有则通过tutoringId获取
        if (schedule.getTeacherId() == null) {
            Integer teacherId = tutoringMapper.getTeacherIdByTutoringId(schedule.getTutoringId());
            if (teacherId == null) {
                return Result.error("未找到对应的教师信息");
            }
            schedule.setTeacherId(teacherId);
        }
        
        try {
            scheduleService.createSchedule(schedule);
            return Result.success("时间安排创建成功，等待教师确认");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 获取教师的时间安排
    @GetMapping("/teacher")
    public Result<List<TutoringSchedule>> getTeacherSchedules() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以查看此信息");
        }
        
        return Result.success(scheduleService.getTeacherSchedules(userId));
    }

    // 获取学生的时间安排
    @GetMapping("/student")
    public Result<List<TutoringSchedule>> getStudentSchedules() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 0) {
            return Result.error("只有学生可以查看此信息");
        }
        
        return Result.success(scheduleService.getStudentSchedules(userId));
    }

    // 获取时间安排详情
    @GetMapping("/{id}")
    public Result<TutoringSchedule> getScheduleDetail(@PathVariable Integer id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        TutoringSchedule schedule = scheduleService.getScheduleById(id);
        if (schedule == null) {
            return Result.error("未找到该时间安排");
        }
        
        // 验证权限：只有相关的学生或教师可以查看
        if ((role == 0 && !schedule.getStudentId().equals(userId)) || 
            (role == 1 && !schedule.getTeacherId().equals(userId))) {
            return Result.error("无权查看此时间安排");
        }
        
        return Result.success(schedule);
    }

    // 教师取消时间安排
    @PutMapping("/{id}/status")
    public Result<String> updateScheduleStatus(@PathVariable Integer id, @RequestParam Integer status) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以操作");
        }
        
        TutoringSchedule schedule = scheduleService.getScheduleById(id);
        if (schedule == null) {
            return Result.error("未找到该时间安排");
        }
        
        if (!schedule.getTeacherId().equals(userId)) {
            return Result.error("无权操作此时间安排");
        }
        
        // 教师只能取消课程安排，不能确认
        if (status == 1) {
            // 如果是学生创建的课程安排，教师可以确认
            if ("STUDENT".equals(schedule.getCreatedBy())) {
                scheduleService.updateScheduleStatus(id, status);
                return Result.success("已确认时间安排");
            }
            return Result.error("教师不能确认自己创建的课程安排，只有学生可以确认");
        }
        
        // 教师可以取消课程安排
        if (status == 3) {
            scheduleService.updateScheduleStatus(id, status);
            return Result.success("已取消时间安排");
        }
        
        return Result.error("无效的操作");
    }

    // 提交课程反馈和评分
    @PutMapping("/{id}/feedback")
    public Result<String> submitFeedback(@PathVariable Integer id, 
                                       @RequestParam String feedback,
                                       @RequestParam Integer rating) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 0) {
            return Result.error("只有学生可以提交反馈");
        }
        
        TutoringSchedule schedule = scheduleService.getScheduleById(id);
        if (schedule == null) {
            return Result.error("未找到该时间安排");
        }
        
        if (!schedule.getStudentId().equals(userId)) {
            return Result.error("无权操作此时间安排");
        }
        
        if (schedule.getStatus() != 1) {
            return Result.error("只有已确认的课程可以提交反馈");
        }
        
        try {
            // 解码反馈内容
            String decodedFeedback = URLDecoder.decode(feedback, StandardCharsets.UTF_8.name());
            scheduleService.submitFeedback(id, decodedFeedback, rating);
            return Result.success("反馈提交成功");
        } catch (Exception e) {
            return Result.error("提交反馈失败: " + e.getMessage());
        }
    }

    // 教师创建时间安排
    @PostMapping("/teacher/create")
    public Result<String> createTeacherSchedule(@RequestBody TutoringSchedule schedule) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以创建时间安排");
        }
        
        schedule.setTeacherId(userId);
        schedule.setStatus(0); // 设置为待确认状态
        schedule.setCreatedBy("TEACHER"); // 设置创建者为教师
        
        try {
            // 验证学生是否有与该教师的已确认预约
            boolean hasBooking = bookingMapper.checkStudentTeacherBooking(
                schedule.getStudentId(), userId, 1) > 0;
            
            if (!hasBooking) {
                return Result.error("该学生没有与您的已确认预约，无法创建课程安排");
            }
            
            tutoringScheduleMapper.insert(schedule);
            return Result.success("时间安排创建成功，等待学生确认");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 学生确认/取消时间安排
    @PutMapping("/student/{id}/status")
    public Result<String> updateStudentScheduleStatus(@PathVariable Integer id, @RequestParam Integer status) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 0) {
            return Result.error("只有学生可以操作");
        }
        
        TutoringSchedule schedule = scheduleService.getScheduleById(id);
        if (schedule == null) {
            return Result.error("未找到该时间安排");
        }
        
        if (!schedule.getStudentId().equals(userId)) {
            return Result.error("无权操作此时间安排");
        }
        
        // 如果是学生创建的课程安排，学生只能取消
        if ("STUDENT".equals(schedule.getCreatedBy())) {
            if (status == 1) {
                return Result.error("学生不能确认自己创建的课程安排，只有教师可以确认");
            }
            if (status == 3) {
                scheduleService.updateScheduleStatus(id, status);
                return Result.success("已取消时间安排");
            }
            return Result.error("无效的操作");
        }
        
        // 如果是教师创建的课程安排，学生可以确认或取消
        if ("TEACHER".equals(schedule.getCreatedBy())) {
            if (status == 1 || status == 3) {
                scheduleService.updateScheduleStatus(id, status);
                return Result.success(status == 1 ? "已确认时间安排" : "已取消时间安排");
            }
            return Result.error("无效的操作");
        }
        
        return Result.error("无效的操作");
    }

    /**
     * 获取学生待确认的课程安排
     */
    @GetMapping("/student/pending")
    public Result getStudentPendingSchedules() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        if (role == null || role != 0) {
            return Result.error("只有学生可以查看待确认的课程安排");
        }
        
        // 查询学生待确认的课程安排
        List<Map<String, Object>> schedules = tutoringScheduleMapper.getStudentPendingSchedules(userId);
        return Result.success(schedules);
    }

    /**
     * 删除课程时间安排
     * 需要在数据库中添加teacher_deleted和student_deleted字段
     * ALTER TABLE tutoring_schedule ADD COLUMN teacher_deleted TINYINT(1) DEFAULT 0;
     * ALTER TABLE tutoring_schedule ADD COLUMN student_deleted TINYINT(1) DEFAULT 0;
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteSchedule(@PathVariable Integer id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        TutoringSchedule schedule = scheduleService.getScheduleById(id);
        if (schedule == null) {
            return Result.error("未找到该时间安排");
        }
        
        // 验证权限：只有相关的学生或教师可以删除
        if (role == 0 && !schedule.getStudentId().equals(userId)) {
            return Result.error("无权删除此时间安排");
        } else if (role == 1 && !schedule.getTeacherId().equals(userId)) {
            return Result.error("无权删除此时间安排");
        }
        
        // 只能删除已完成或已取消的预约
        if (schedule.getStatus() != 2 && schedule.getStatus() != 3) {
            return Result.error("只能删除已完成或已取消的时间安排");
        }
        
        // 根据角色区分删除方式
        if (role == 1) {
            scheduleService.teacherDeleteSchedule(id);
        } else {
            scheduleService.studentDeleteSchedule(id);
        }
        
        return Result.success("删除成功");
    }

    /**
     * 检查课程安排的支付状态
     * @param id 课程安排ID
     * @return 支付状态信息
     */
    @GetMapping("/{id}/payment-status")
    public Result<Map<String, Object>> checkPaymentStatus(@PathVariable Integer id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        // 获取课程安排
        TutoringSchedule schedule = scheduleService.getScheduleById(id);
        if (schedule == null) {
            return Result.error("未找到该课程安排");
        }
        
        // 验证权限
        if ((role == 0 && !schedule.getStudentId().equals(userId)) || 
            (role == 1 && !schedule.getTeacherId().equals(userId))) {
            return Result.error("无权查看此课程安排");
        }
        
        // 查找相关支付订单
        PaymentOrder paymentOrder = null;
        if (schedule.getBookingId() != null) {
            // 如果课程安排关联了预约ID，通过预约ID查询
            paymentOrder = paymentOrderMapper.findByBookingId(schedule.getBookingId());
        } else {
            // 否则检查是否有专门为该课程安排创建的支付订单
            // 通过课程安排ID查询相关订单
            String scheduleIdStr = String.valueOf(schedule.getId());
            
            List<PaymentOrder> orders = paymentOrderMapper.findByStudentId(schedule.getStudentId());
            if (orders != null && !orders.isEmpty()) {
                for (PaymentOrder order : orders) {
                    // 检查该订单是否与当前课程安排匹配
                    if (order.getTeacherId().equals(schedule.getTeacherId())) {
                        // 有三种可能匹配的情况
                        // 1. 通过订单号中的SCH+scheduleId标识匹配
                        boolean isOrderForThisSchedule = order.getOrderNo() != null && 
                                                        order.getOrderNo().contains("SCH" + scheduleIdStr);
                        
                        // 2. 通过bookingId匹配（如果课程安排有bookingId）
                        boolean isBookingMatch = schedule.getBookingId() != null && 
                                                order.getBookingId() != null &&
                                                order.getBookingId().equals(schedule.getBookingId());
                        
                        // 3. 特殊情况：bookingId可能就是scheduleId（在找不到关联预约时的处理）
                        boolean isSpecialCase = order.getBookingId() != null && 
                                               order.getBookingId().equals(schedule.getId());
                        
                        if (isOrderForThisSchedule || isBookingMatch || isSpecialCase) {
                            // 找到匹配的订单
                            paymentOrder = order;
                            break;
                        }
                    }
                }
            }
        }
        
        // 返回支付状态
        Map<String, Object> result = new HashMap<>();
        boolean isPaid = paymentOrder != null && paymentOrder.getStatus() == 1;
        boolean needsPayment = PaymentHelper.needsPayment(schedule, paymentOrder);
        String paymentStatusDesc = PaymentHelper.getPaymentStatusDescription(schedule, paymentOrder);
        
        result.put("isPaid", isPaid);
        result.put("needsPayment", needsPayment);
        result.put("paymentStatusDescription", paymentStatusDesc);
        result.put("orderInfo", paymentOrder);
        result.put("scheduleStatus", schedule.getStatus());
        
        return Result.success(result);
    }

    // 检查时间冲突
    @PostMapping("/check-conflict")
    public Result<Boolean> checkTimeConflict(@RequestBody TutoringSchedule schedule) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以执行此操作");
        }
        
        // 设置当前教师ID
        schedule.setTeacherId(userId);
        
        try {
            // 检查是否有时间冲突
            List<TutoringSchedule> conflicts = tutoringScheduleMapper.checkTimeConflict(
                userId, 
                schedule.getStartTime(), 
                schedule.getEndTime()
            );
            
            // 如果有冲突，返回冲突信息
            if (conflicts != null && !conflicts.isEmpty()) {
                // 返回冲突详情
                return Result.success(false, "检测到时间冲突", conflicts);
            }
            
            return Result.success(true);
        } catch (Exception e) {
            return Result.error("检查时间冲突失败: " + e.getMessage());
        }
    }
    
    // 获取某个时间范围内的所有课程安排
    @GetMapping("/range")
    public Result<List<TutoringSchedule>> getSchedulesByDateRange(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以执行此操作");
        }
        
        try {
            LocalDateTime start = LocalDateTime.parse(startDate.replace(" ", "T"));
            LocalDateTime end = LocalDateTime.parse(endDate.replace(" ", "T"));
            
            List<TutoringSchedule> schedules = tutoringScheduleMapper.getSchedulesByDateRange(
                userId, start, end
            );
            
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取时间范围内的课程安排失败: " + e.getMessage());
        }
    }
} 